package com.ruoyi.framework.security.handle;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.List;

@Log4j2
@Component
public class SmsLoginHanlder extends LoginHanlder implements LoginStrategy {

    @Autowired
    private RedisCache redisCache;

    @Override
    public String getLoginType() {
        return "sms";
    }

    @Override
    public String login(String phone, String password, String code, String uuid) {
        checkCode(phone, code);
        log.info("这是短信登录");
        //查询用户
        SysUser sysUser = selectUserByPhone(phone);
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new UserPasswordNotMatchException();
        }
        // 用户验证
        Authentication authentication = null;
        try {
            authentication = authenticate(new LoginAuthenticationToken(sysUser.getUserName(), "sms"));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return getToken(loginUser);
    }

    @SneakyThrows
    private void checkCode(String phone, String code) {

        if (StringUtils.isBlank(code)) {
            throw new RuntimeException("验证码不能为空");
        }
        if (isSuperAccount(phone)) {
            return;
        }
        String key = "SMS_CODE_KEY:" + phone;
        redisCache.redisTemplate.setKeySerializer(new StringRedisSerializer());

        if (!redisCache.redisTemplate.hasKey(key)) {
            throw new RuntimeException("验证码不正确");
        }
        Object codeObj = redisCache.redisTemplate.opsForValue().get(key);

        if (codeObj == null) {
            throw new RuntimeException("验证码不正确");
        }
        String saveCode = codeObj.toString();
        if (StringUtils.isBlank(saveCode)) {
            redisCache.redisTemplate.delete(key);
            throw new RuntimeException("验证码不正确");
        }
        if (!StringUtils.equals(saveCode, code)) {
            throw new RuntimeException("验证码不正确");
        }
        redisCache.redisTemplate.delete(key);
    }

    private Boolean isSuperAccount(String mobile) {
        List<String> accountList = redisCache.redisTemplate.opsForList().range("SUPER_ACCOUNT:", 0, -1);
        if (accountList != null) {
            for (String s : accountList) {
                if (mobile.contains(s)) {
                    return true;
                }
            }
        }
        return false;
    }
}